package com.easylinkin.linkappapi.schedule;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.easylinkin.bases.redis.util.RedisUtil;
import com.easylinkin.linkappapi.jkmonior.entity.JkMonitorConfig;
import com.easylinkin.linkappapi.jkmonior.mapper.JkMonitorConfigMapper;
import com.easylinkin.linkappapi.schedule.service.JobCallService;
import com.easylinkin.linkappapi.shigongyun.vo.MonitorInfoVo;
import com.easylinkin.linkappapi.tenant.mapper.LinkappTenantMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 业务自动任务
 *
 * @author zhengwen
 **/
@Configuration
@EnableScheduling
@ConditionalOnProperty(prefix = "scheduling.business", name = "enabled", havingValue = "true")
@Slf4j
public class BusinessTask {

    @Autowired
    private RedisUtil redisUtil;

    @Resource
    private JobCallService jobCallService;

    @Resource
    private LinkappTenantMapper tenantMapper;

    @Resource
    private JkMonitorConfigMapper jkMonitorConfigMapper;

    /**
     * 对接第三方接口，采集基坑监测数据
     *
     * @return 统一出参
     */
    //@Scheduled(fixedDelayString = "${scheduling.business.jkMonitorDataJob.fixedDelay}")
    @Scheduled(cron = "${scheduling.business.jkMonitorDataJob.cron}")
    public RestMessage jkMonitorDataJob() {
        try {
            log.info("--基坑监测数据定时任务开始执行---------jkMonitorDataJob------start-----------");
            Date now = DateUtil.date();
            String key = "siteMonitor:config:jk:tenantProjectIds";
        /* 测试保持配置json字符串
        String confStr = "[" +
                "        {" +
                "            \"tenantId\": \"405cd2c8633ecbee1c5f61c4a87c9019\"," +
                "            \"projectId\": \"1516216647654924290\"," +
                "            \"monitorDataUrl\": \"http://111.47.25.55:50030/oauth/wkProjectItem/getMonitorDataByProjectId3?projectId=\"," +
                "            \"monitorPointTypeUrl\": \"http://111.47.25.55:50030/oauth/wkProjectItem/getMonitorResultByProjectId?projectId=\"" +
                "        }" +
                "    ]";
        redisUtil.set(key,confStr);*/

/*
            Object tenantProjectConfigObj = redisUtil.get(key);
            if (tenantProjectConfigObj == null) {
                log.error("-----没有配置基坑监测信息,先执行老逻辑");
                MonitorInfoVo monitorInfoVo = new MonitorInfoVo();
                String tanantIdKey = "siteMonitor:config:monitorData:tenantId";
                Object tenantIdObj = redisUtil.get(tanantIdKey);
                if (tenantIdObj != null) {
                    monitorInfoVo.setTenantId(tenantIdObj.toString());
                } else {
                    monitorInfoVo.setTenantId("1");
                }
                String projectIdKey = "siteMonitor:config:monitorData:projectId";
                Object projectIdObj = redisUtil.get(projectIdKey);
                if (projectIdObj != null) {
                    monitorInfoVo.setProjectId(projectIdObj.toString());
                } else {
                    monitorInfoVo.setProjectId("1522548212357922817");
                }
                jkMonitorData(monitorInfoVo);
                return RestBuilders.failureBuilder().message("没有配置基坑监测信息").build();
            }

            if (JSONUtil.isJsonArray(tenantProjectConfigObj.toString())) {
                List<MonitorInfoVo> tenantProjectLs = JSONUtil.toList(tenantProjectConfigObj.toString(), MonitorInfoVo.class);

                for (int i = 0; i < tenantProjectLs.size(); i++) {
                    MonitorInfoVo confVo = tenantProjectLs.get(i);
                    confVo.setAutoTime(now);
                    jobCallService.jkMonitorDataConfigTrans(confVo);
                }
            }*/
            //20221031变更，不再读取缓存配置进行数据获取，改为读取配置
            QueryWrapper<JkMonitorConfig> configQw = new QueryWrapper<>();
            configQw.eq("delete_state", 1);
            configQw.orderByDesc("create_time");
            List<JkMonitorConfig> configList = jkMonitorConfigMapper.selectList(configQw);
            log.info("---查询到基坑检测配置数量：{}", configList == null ? 0 : configList.size());
            if (CollectionUtil.isNotEmpty(configList)) {
                //去重
                List<JkMonitorConfig> ls = configList.stream().collect(
                        Collectors.collectingAndThen(
                                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(JkMonitorConfig::getProjectId))), ArrayList::new));
                log.info("---查询到基坑检测配置数量(去重)：{}", ls == null ? 0 : ls.size());
                ls.stream().forEach(c -> {
                    MonitorInfoVo confVo = new MonitorInfoVo();
                    confVo.setTenantId(c.getTenantId());
                    confVo.setProjectId(c.getProjectId());

                    String dataUrl = c.getDataMonitorUrl();
                    if (StringUtils.isNotEmpty(dataUrl)) {
                        if (!dataUrl.endsWith("=")) {
                            dataUrl = dataUrl.replaceAll(c.getProjectId(), "");
                        }
                    }
                    confVo.setMonitorDataUrl(dataUrl);

                    String typeUrl = c.getItemMonitorUrl();
                    if (StringUtils.isNotEmpty(typeUrl)) {
                        if (!typeUrl.endsWith("=")) {
                            typeUrl = typeUrl.replaceAll(c.getProjectId(), "");
                        }
                    }
                    confVo.setMonitorPointTypeUrl(typeUrl);
                    confVo.setAutoTime(now);
                    //jobCallService.jkMonitorDataConfigTrans(confVo);
                    //TODO 开线程处理不用等待上一个租户的处理完
                    ThreadUtil.execAsync(() -> {
                        log.info("---基坑检测异步执行：{}", JSONUtil.toJsonStr(confVo));
                        exeJkMonitorDataTask(confVo);
                    }, true);
                });
            }

            log.info("--基坑监测数据定时任务完成---------jkMonitorDataJob------end-----------");
            return RestBuilders.successBuilder().build();
        } catch (Exception e) {
            e.printStackTrace();
            log.info("--基坑监测数据定时任务异常---------jkMonitorDataJob------error-----------", e);
            return null;
        }
    }

    private void exeJkMonitorDataTask(MonitorInfoVo confVo) {
        jobCallService.jkMonitorDataConfigTrans(confVo);
    }

    /**
     * 基坑监测数据获取
     *
     * @param monitorInfoVo
     * @return
     */
    private RestMessage jkMonitorData(MonitorInfoVo monitorInfoVo) {
        return jobCallService.jkMonitorDataConverSave(monitorInfoVo);
    }
}
